//
//  WJBLabelMarkView.swift
//  WJBProject
//
//  Created by 无尽宝 on 2020/4/14.
//  Copyright © 2020 VolantPig. All rights reserved.
//

import UIKit

@objc protocol WJBLabelMarkViewDelegate: NSObjectProtocol {
    @objc optional func didSelectedAtIndexPath(indexPath: IndexPath, labelText: String, markString: String?)
    func customView(cell: UICollectionViewCell, cellForRowAt index: Int, dataSource: [String], markString: String?)
}

// ps: 此view,布局已经提取出去，传入参数主要用于布局计算

class WJBLabelMarkView: UIView {

    weak var myDelegate: WJBLabelMarkViewDelegate?
    var myCollectionView: UICollectionView?
    lazy var layout: WJBFlowViewLayout = {
        let lazyLayout = WJBFlowViewLayout()
//        lazyLayout.sectionInsets = UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
        return lazyLayout
    }()
    /// 标记字段，可选
    var markString: String?
    var dataSource: [String] = [String]()
    var textFont: UIFont = systemFont(12)
    var textColor: UIColor = .black
    
    /// item圆角半径
    var cornerRadius: CGFloat = 0
    
    /// 固定高度
    var fixedHeight: CGFloat?
    /// 文字左右单边距离
    var extraWidth: CGFloat = 7
    /// 额外的插入的高度，用于灵活调整
    var extraInsertWidth: CGFloat = 0
    /// 固定size
    var fixedSize: CGSize?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUIElements()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUIElements() {
        
        myCollectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height), collectionViewLayout: self.layout)
        myCollectionView?.backgroundColor = .clear
        myCollectionView?.delegate = self
        myCollectionView?.dataSource = self
        
        myCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "labelMark")
        self.addSubview(self.myCollectionView!)
//        myCollectionView?.snp.makeConstraints({ (make) in
//            make.left.right.top.bottom.equalTo(self)
//        })
        myCollectionView?.bounces = false
//        self.myCollectionView?.reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.myCollectionView?.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        self.layoutIfNeeded()
//        self.myCollectionView?.reloadData()
        self.myCollectionView?.frame.size = CGSize.init(width: self.frame.size.width, height: self.layout.sectionHeight)
    }
    
}

extension WJBLabelMarkView: UICollectionViewDelegate, UICollectionViewDataSource, WJBFlowViewLayoutDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
           return 1
    }
       
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
       
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "labelMark", for: indexPath)
        
        for subV in cell.contentView.subviews {
            subV.removeFromSuperview()
        }
        
        cell.makeCorner(self.cornerRadius)
        cell.tag = self.tag
        self.myDelegate?.customView(cell: cell, cellForRowAt: indexPath.row, dataSource: self.dataSource, markString: self.markString)
        
        return cell
        
//           // 使用 贝塞尔曲线 设置圆角
////        cell.makeCornerRadius(postion: .allCorners, cornerRadii: self.fixedSize == nil ? CGSize.init(width: (self.fixedHeight ?? 0)/2.0, height: (self.fixedHeight ?? 0)/2.0) : CGSize.init(width: (self.fixedSize?.height ?? 0)/2.0, height: (self.fixedSize?.height ?? 0)/2.0))
//
//        cell.layer.cornerRadius = self.cornerRadius //self.fixedSize == nil ? (self.fixedHeight ?? 0)/2.0 : (self.fixedSize?.height ?? 0)/2.0
//
//        let label = UILabel()
//        cell.addSubview(label)
//        label.snp.makeConstraints { (make) in
//            make.left.right.top.bottom.equalTo(cell)
//        }
//        label.labelConfig(textAlignment: .center, font: self.textFont, textColor: self.textColor)
//        label.text = self.dataSource[indexPath.row]
//
//        cell.backgroundColor  = .yellow
//
//        return cell
    }
       
    func collectionViewSizeForItemAtIndexPath(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, indexPath: IndexPath) -> CGSize {

        // ps: 这里可以随意修改，目前，只有两个选择，要么固定尺寸，要么固定高度，后期可以根据需求进行添加，固定宽度、都不固定，具体要具体考虑，并且注意cell的圆角问题
        guard let itemSize = self.fixedSize else {
            // 非固定尺寸，但是固定高度了
            let str = self.dataSource[indexPath.row]
            let labelWidth = JDTools.getTextRectSize(text: NSString.init(string: str), font: textFont, size: .zero).width + extraWidth*2
//            print("数据个数:\(CGSize.init(width: labelWidth, height: self.fixedHeight ?? 0))")
            return CGSize.init(width: labelWidth + extraInsertWidth, height: self.fixedHeight ?? 0)
        }
        // 固定尺寸直接返回
        return itemSize
    }
       
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("当前点击\(indexPath.row)")
        let text = self.dataSource[indexPath.row]
        self.myDelegate?.didSelectedAtIndexPath?(indexPath: indexPath, labelText: text, markString: self.markString)
    }
    
}

// 使用方式
//let flowView = WJBLabelMarkView()
//self.view.addSubview(flowView)
//flowView.snp.makeConstraints { (make) in
//    make.left.right.equalTo(self.view)
//    make.top.equalTo(self.view).offset(plusFitWidth(200))
//    make.height.equalTo(0)
//}
//flowView.cornerRadius = plusFitWidth(5)
//flowView.fixedHeight = plusFitWidth(30)
//flowView.myDelegate = self
//
//flowView.dataSource = ["xxx"]
//
//flowView.layoutIfNeeded()
//flowView.snp.updateConstraints { (make) in
//    make.height.equalTo(flowView.layout.sectionHeight)
//}
//flowView.clipsToBounds = true
